package com.candy.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//        将servletRequest与servletResponse转换成HttpServletRequest和HttpServletResponse
        HttpServletRequest req=(HttpServletRequest)request;
        HttpServletResponse resp=(HttpServletResponse)response;
//        获取session对象
        HttpSession session=req.getSession();
//        确认用户是否为登录状态，并将状态进行保存
        boolean logined=(session!=null) && (session.getAttribute("user")!=null);
//        获取用户的请求路径
        String requestUrl=req.getRequestURI();
//        判断当用户没有登录并且用户的访问路径不是一个登录页面且请求的资源也不是登录的servlet则重定向到登录的界面上
        if((!logined) && (!requestUrl.endsWith("index.jsp")) && (!requestUrl.endsWith("login"))){
//            重定向到登录界面
            resp.sendRedirect(req.getContextPath()+"/index.jsp");
            return;
        }
        chain.doFilter(request, response);

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("这里是登录拦截过滤器的初始化方法");
    }

    @Override
    public void destroy() {
        System.out.println("这里是登录拦截过滤器的销毁方法");
    }
}
